package com.zixuan.sina.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zixuan.sina.config.redis.RedisService;
import com.zixuan.sina.dao.PostMapper;
import com.zixuan.sina.dao.UserMapper;
import com.zixuan.sina.entity.Permission;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.entity.vo.PostQuery;
import com.zixuan.sina.entity.vo.PostVo;
import com.zixuan.sina.entity.vo.UserInfoView;
import com.zixuan.sina.entity.vo.UserInfoVo;
import com.zixuan.sina.service.*;
import com.zixuan.sina.utils.JwtUtils;
import com.zixuan.sina.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
public class SysUserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Value("${request.login.tokenKey}")
    private String tokenKey;
    @Resource
    PermissionService permissionService;
    @Resource
    PostMapper postMapper;
    @Resource
    RedisService redisService;
    @Resource
    private  PostServiceImpl  postService;
    @Resource
    TopicService topicService;
    @Resource
    CommentService commentService;
    @Resource
    private PasswordEncoder passwordEncoder;


    //    @Resource
//    UserMapper userMapper;
    @Override
    public Result getInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();//从上下文中取出用户信息
        User user = (User) authentication.getPrincipal();
        List<Permission> permissionList = permissionService.findPermissionByUserId(user.getId());//获得当前用户的权限列表
        Object[] roles = permissionList.stream()
                .filter(Objects::nonNull)
                .map(Permission::getCode)
                .filter(Objects::nonNull).toArray();
        UserInfoVo userInfo = new UserInfoVo(user.getId(), user.getNickName(), user.getAvatar(), null, roles);
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setRoleNames(getRoles(user.getId()));
        String thumbs = user.getThumbs();
        List<String> thumbList = JSON.parseArray(thumbs, String.class);
        userInfo.setThumbList(thumbList);
        return Result.ok(userInfo).message("用户信息查询成功");
    }

    @Override
    public Result logout(String token) {
        SecurityContextHolder.getContext().setAuthentication(null);
        redisService.del(tokenKey + token);
        return Result.ok();
    }

    @Override
    public Result getUserInfoById(String id, int isSpecial, String type) {
        String ipQueryUrl = "https://token.ip.api.useragentinfo.com/json?token=ab28a017dc0b7536f452fd951aed51d2";
        String body = HttpUtil.createGet(ipQueryUrl).execute().body();
        HashMap<String, Object> map = JSONUtil.toBean(body, HashMap.class);
        Integer code = ((Integer) map.get("code"));
        String province = null;
        String city = null;
        String area = null;
        String country = null;
        String ip = null;
        if (200 == code) {
            province = (String) map.get("province");
            city = (String) map.get("city");
            area = (String) map.get("area");
            country = (String) map.get("country");
            ip = (String) map.get("ip");
        }

        User user = baseMapper.selectById(id);
        if (user == null) {
            return Result.error().message("当前用户不存在");
        }
        UserInfoView userInfoView = new UserInfoView();
        BeanUtils.copyProperties(user, userInfoView);
        //[1,2,3,4]
        String thumbs = user.getThumbs();
        List<String> thumbList = JSON.parseArray(thumbs, String.class);
        userInfoView.setThumbList(thumbList);
        userInfoView.setIp(ip);
        userInfoView.setProvince(province);
        userInfoView.setCity(city);
        userInfoView.setCountry(country);
        userInfoView.setArea(area);
        //查询当前用户发布的帖子信息
        PostQuery postQuery = new PostQuery();
        postQuery.setUserId(user.getId());
        postQuery.setIsSpecial(isSpecial);
        postQuery.setType(type);
        List<PostVo> postVos = postMapper.queryPostMyPush(postQuery);
        List<PostVo> postVoResult = postService.getPostVoResult(postVos);
        userInfoView.setPostVos(postVoResult);
        return Result.ok().data(userInfoView);
    }

    @Override
    public Result getUserList(String key) {
//        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(User::getNickName,key).or()
//                .eq(User::getIsAdmin,key).or()
//                .eq(User::getPhone,key);
        return Result.ok(baseMapper.selectList(null));
    }

    @Override
    public Result getUserById(String id) {

        return Result.ok(baseMapper.selectById(id));
    }


    @Override
    public User findUserByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public Result deleteUser(Long id) {
        return null;
    }

    @Override
    public Result addUser(User user) {
        if (ObjectUtil.isEmpty(user)) {
            return Result.error().message("用户信息为空");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            //自动生成账号
            //查询当前账号是否存在系统 校验唯一性
            Long count = 0L;
            String account = "";
            do {
                account = buildAccount();
                LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(User::getUsername, account);
                count = baseMapper.selectCount(wrapper);
            } while (count > 0);
            user.setUsername(account);
        }

        String password = user.getPassword();
        password = passwordEncoder.encode(password);
        user.setPassword(password);
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);
        baseMapper.insert(user);
        return Result.ok(user.getUsername()).message("注册成功");
    }

    private String buildAccount() {
        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 100000;
        String account = String.format("%06d", randomNumber);
        return account;
    }

    @Override
    public Result editUserInfo(User user) {

        if(!StrUtil.isBlank(user.getPassword())){
        //如果前端传入的密码和数据库不一样 才需要对密码进行加密 如果一样 说明密码没变
        User userDb = baseMapper.selectById(user.getId());
        if(ObjectUtil.isNotNull(userDb)){
            String password = userDb.getPassword();
            if(!password.equals(user.getPassword())){
                String encode = passwordEncoder.encode(user.getPassword());
                user.setPassword(encode);
            }
        }
        }

        int i = baseMapper.updateById(user);
        return i > 0 ? Result.ok() : Result.error();
    }

    @Override
    public Result delete(Long id) {
        return null;
    }

    @Override
    public Result findUserInfoById(Long id) {
        return null;
    }

    @Override
    public User findUserById(String userId) {

        return baseMapper.findUserById(userId);
    }

    @Override
    public Result getLoginUser() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(principal, userInfoVo);
        userInfoVo.setName(principal.getNickName());
//        userInfoVo.setRoleNames(getRoles(principal.getId()));
        return Result.ok(userInfoVo);
    }

    @Override
    public String getRoles(String userId) {
        List<String> roles = baseMapper.getRoles(userId);
        return roles.toString();
    }
//    @Override
//    public Result getMenuInfo() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();//从上下文中取出用户信息
//        User user = (User) authentication.getPrincipal();
//        List<Permission> permissionList = user.getPermissionList();
//        permissionList = permissionList.stream()
//                .filter(item-> item!=null && item.getType()!=2).collect(Collectors.toList());
//        List<RouterVo> routerVos = MenuTree.makeRouter(permissionList, 0L);
//        return Result.ok(routerVos).message("路由信息查询成功");
//
//    }

//    @Override
//    public User findUserById(Integer userId) {
//        return userMapper.selectOne(new QueryWrapper<User>().eq("id",userId));
//    }
//


}
